terraform {
  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 5.0"
    }
  }
}


# Configure the AWS Provider
provider "aws" {
  region = "ap-northeast-1"
  shared_config_files      = ["/home/wayne/.jos/config"]
  shared_credentials_files = ["/home/wayne/.jos/credentials"]
  profile                  = "default"
}

# Configure ssh_key
resource "aws_key_pair" "ssh_key" {
  key_name   = "ssh_key"
  public_key = file("~/.ssh/id_rsa.pub")
}

# Get aws free ami
data "aws_ami" "ubuntu" {
  most_recent = true
  filter {
    name = "name"
    values = [ "ubuntu/images/hvm-ssd/ubuntu-*-22.04-amd64-server-*2023*" ]
#    values = [ "ubuntu*22.04*amd64*server*" ]
  }

  owners = [ "099720109477" ]
}

# Network

resource "aws_vpc" "app_vpc" {
  cidr_block = "10.123.0.0/16"
}

resource "aws_internet_gateway" "igw" {
  vpc_id = aws_vpc.app_vpc.id
}

resource "aws_subnet" "public_subnet" {
  vpc_id            = aws_vpc.app_vpc.id
  cidr_block        = "10.123.0.0/24"
  map_public_ip_on_launch = true
  availability_zone = "ap-northeast-1a"
}

resource "aws_route_table" "public_rt" {
  vpc_id = aws_vpc.app_vpc.id

  route {
    cidr_block = "0.0.0.0/0"
    gateway_id = aws_internet_gateway.igw.id
  }
}

resource "aws_route_table_association" "public_rt_asso" {
  subnet_id      = aws_subnet.public_subnet.id
  route_table_id = aws_route_table.public_rt.id
}


# Security Group

resource "aws_security_group" "allow-http" {
  name        = "allow-http"
  description = "Allow incoming HTTP traffic"
  vpc_id = aws_vpc.app_vpc.id
  
  ingress {
    description      = "HTTP from VPC"
    from_port        = 80
    to_port          = 80
    protocol         = "tcp"
    cidr_blocks      = ["0.0.0.0/0"]
    ipv6_cidr_blocks = ["::/0"]
  }

  ingress {
    from_port   = 22
    to_port     = 22
    protocol    = "tcp"
    cidr_blocks = ["0.0.0.0/0"]
    ipv6_cidr_blocks = ["::/0"]  
  }  

  egress {
    from_port        = 0
    to_port          = 0
    protocol         = "-1"
    cidr_blocks      = ["0.0.0.0/0"]
    ipv6_cidr_blocks = ["::/0"]
  }
}


# EC2

resource "aws_instance" "apache" {
  ami                         = data.aws_ami.ubuntu.id
  instance_type               = "t2.micro"
  key_name                  = "ssh_key"
  subnet_id                   = aws_subnet.public_subnet.id
  vpc_security_group_ids      = [aws_security_group.allow-http.id]
  associate_public_ip_address = true

  user_data = <<-EOF
  #!/bin/bash
  echo "*** Installing apache2"
  sudo apt update  -y
  sudo apt install apache2 git -y
  echo "*** Completed Installing apache2"
  sudo rm -rf /var/www/html
  git clone https://gitee.com/weibone/web.git /var/www/html
  EOF
}

# Out put

output "public_ip" {
  value = aws_instance.apache.public_ip
}

output "ami" {
  value = data.aws_ami.ubuntu.id
}